package com.zhsj.OkeHomeConsumption.utils;

import android.content.Context;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.view.View;
import android.widget.Toast;

import com.zhsj.OkeHomeConsumption.common.Constants;
import com.zhsj.OkeHomeConsumption.common.MyApplication;
import com.zhsj.OkeHomeConsumption.common.OkeHomeConsumptionApi;
import com.zhsj.OkeHomeConsumption.empty.VersionInfo;
import com.zhsj.OkeHomeConsumption.network.HttpClient;
import com.zhsj.OkeHomeConsumption.network.JsonResponseHandler;
import com.zhsj.OkeHomeConsumption.other.URLEntity;
import com.zhsj.OkeHomeConsumption.update.ConfirmCallback;
import com.zhsj.OkeHomeConsumption.update.ConfirmDialog;

import org.json.JSONException;
import org.json.JSONObject;
import org.json.JSONTokener;

import java.util.HashMap;

/**
 * Created by rxy on 17/7/26.
 */

public class UpdateAppUtils {

    /**
     * 获取当前apk的版本号 currentVersionCode
     *
     * @param ctx
     * @return
     */
    public static int getAPPLocalVersion(Context ctx) {
        int currentVersionCode = 0;
        PackageManager manager = ctx.getPackageManager();
        try {
            PackageInfo info = manager.getPackageInfo(ctx.getPackageName(), 0);
            String appVersionName = info.versionName; // 版本名
            currentVersionCode = info.versionCode; // 版本号
        } catch (PackageManager.NameNotFoundException e) {
            e.printStackTrace();
        }
        return currentVersionCode;
    }

    /**
     * 获取当前apk的版本号 currentVersionCode
     *
     * @param ctx
     * @return
     */
    public static String getAPPLocalVersionName(Context ctx) {
        int currentVersionCode = 0;
        String appVersionName = "";
        PackageManager manager = ctx.getPackageManager();
        try {
            PackageInfo info = manager.getPackageInfo(ctx.getPackageName(), 0);
            appVersionName = info.versionName; // 版本名
            currentVersionCode = info.versionCode; // 版本号
        } catch (PackageManager.NameNotFoundException e) {
            e.printStackTrace();
        }
        return appVersionName;
    }

    /**
     * 获取服务器上版本信息
     *
     * @param context
     * @param callBack
     */
    public static void getAPPServerVersion(Context context, final VersionCallBack callBack) {
        HashMap<String, String> mLogOnHashMap = new HashMap<String, String>();
        mLogOnHashMap.put("v", Constants.APPVERSION);
        mLogOnHashMap.put("t", Constants.TIME);
        mLogOnHashMap.put("deviceId", URLEntity.getInstance().getImei());
        mLogOnHashMap.put("platform", Constants.PLAFORM);
        mLogOnHashMap.put("deviceToken", Constants.DEVICETOKEN);
        mLogOnHashMap.put("client", Constants.CLIENT);
        // 获取sign签名
        Constants.SIGN = SignUtil.getInstance().getSign(mLogOnHashMap);
        HashMap<String, String> params = new HashMap<>();
        HttpClient.post(OkeHomeConsumptionApi.ELVDOU_CHECK_VERSION, params, new JsonResponseHandler() {

            @Override
            public void onSuccess(int statusCode, String content) {
                super.onSuccess(statusCode, content);
                LogUtils.e("mylog", "content=" + content);
                JSONTokener jsonT = new JSONTokener(content);
                JSONObject jsonOBJ = null;
                VersionInfo versionInfo;
                try {
                    jsonOBJ = (JSONObject) jsonT.nextValue();
                } catch (JSONException e) {
                    e.printStackTrace();
                }
                if (jsonOBJ != null) {
                    String code = jsonOBJ.optString("code");
                    String message = jsonOBJ.optString("message");
                    if (code.equals("N000000")) {
                        JSONObject data = jsonOBJ.optJSONObject("data");
                        versionInfo = JsonUtils.object(data.toString(), VersionInfo.class);
                        if (versionInfo != null)
                            callBack.callBack(versionInfo);
                    }
                }
            }

            @Override
            public void onFailure(Throwable e) {
                super.onFailure(e);
            }
        });

//        HttpUtil.getObject(Api.GETVERSION.mapClear().addBody(), VersionInfo.class, new HttpUtil.ObjectCallback() {
//            @Override
//            public void result(boolean b, @Nullable Object obj) {
//                if (b){
//                    callBack.callBack((VersionInfo) obj);
//                }
//            }
//        });
    }

    /**
     * 判断版本号，更新APP
     *
     * @param context
     */
    public static void updateApp(final Context context) {
        UpdateAppUtils.getAPPServerVersion(context, new UpdateAppUtils.VersionCallBack() {
            @Override
            public void callBack(final VersionInfo info) {
                int localVersion = UpdateAppUtils.getAPPLocalVersion(MyApplication.getContext());
                int serviceVersion = info.getVersion();
                final int state = info.getState();
                LogUtils.i("mylog", "localVersion=" + localVersion + "----serviceVersion=" + serviceVersion);
                if (serviceVersion > localVersion) {
                    final ConfirmDialog dialog = new ConfirmDialog(context, new ConfirmCallback() {
                        @Override
                        public void callback() {
                            DownloadAppUtils.downloadForAutoInstall(MyApplication.getContext(),
                                    info.getUrl(), "oke_home_consum.apk", "更新聚联惠");
                        }
                    });
                    dialog.cancleBtn.setOnClickListener(new View.OnClickListener() {
                        @Override
                        public void onClick(View v) {
                            if (state == 1) {
                                Toast.makeText(context, "必须升级才能使用", Toast.LENGTH_SHORT).show();
                            } else {
                                dialog.cancel();
                            }
                        }
                    });
                    dialog.setVersion(info.getClientVersion());
                    dialog.setTime(info.getUpdateTime());
                    dialog.setContent(info.getReleaseNotes());
                    dialog.setCancelable(false);
                    dialog.show();
                }
            }
        });
    }

    public interface VersionCallBack {
        void callBack(VersionInfo info);
    }
}
